package cn.stylefeng.guns.sys.modular.system.service;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.sys.core.exception.enums.BusExceptionEnum;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.entity.BtyCWGainLoss;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyCWGainLossMapper;
import cn.stylefeng.guns.sys.modular.system.service.impl.GcWxServiceImpl;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BtyCWGainLossService extends ServiceImpl<BtyCWGainLossMapper, BtyCWGainLoss> {

    @Resource
    private BtyCWGainLossMapper btyCWGainLossMapper;

    private static Logger logger = LoggerFactory.getLogger(GcWxServiceImpl.class);

    /**
     * 获取损益列表
     */
    public Page<Map<String, Object>> list(BtyCWGainLoss btyCWGainLoss) {
        Page page = LayuiPageFactory.defaultPage();
        return this.baseMapper.list(page, btyCWGainLoss);
    }

    /**
     * 获取损益列表（不分页）
     */
    public List<BtyCWGainLoss> listAll(BtyCWGainLoss btyCWGainLoss) {
        List<BtyCWGainLoss> list=this.baseMapper.listAll(btyCWGainLoss);
        return list;
    }

    /**
     * 导入损益excel
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Boolean importExcel(String fileName, MultipartFile file) throws Exception {
        boolean notNull = false;
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }

        int sheets = wb.getNumberOfSheets();

        Map<Integer, String> colIdXuhaoMap = new HashMap<Integer, String>();
        Map<Integer, String> colIdDianmingMap = new HashMap<Integer, String>();

        int row_l = 1;
        for (int i = 0; i < sheets; i++) {
            Sheet sheet = wb.getSheetAt(i);
            if (sheet != null) {
                notNull = true;
            }

            int lastRowNum = sheet.getLastRowNum();
            String date = sheet.getRow(1).getCell(0).toString().split("会计期间：")[1];
            row_l++;

            int maxCol = 0;
            {
                int col = 2;
                Row row_bianhao = sheet.getRow(row_l);
                Row row_mendian = sheet.getRow(row_l+1);
                String mendian ;
                String number ;
                boolean isCon = true;
                 while (isCon){
                    number = row_bianhao.getCell(col).toString();
                     if(number.contains(".")){
                         number = number.substring(0,number.indexOf("."));
                     }
                    if (ToolUtil.isNotEmpty(number) || "本月金额:合计".equals(sheet.getRow(row_l+1).getCell(col).toString())) {
                        colIdXuhaoMap.put(col, number);
                        mendian = row_mendian.getCell(col).toString();
                        colIdDianmingMap.put(col, mendian);
                    } else {
                        isCon = false;
                    }
                    col++;
                    maxCol++;
                }
            }
            row_l++;
            row_l++;

            for (int r = row_l; r <= lastRowNum; r++) {
                Row row = sheet.getRow(r);
                if (ToolUtil.isNotEmpty(row)) {
                    int col = 0;
                    String sr ;
                    String hang = "";
                    //报表项目
                    if (ToolUtil.isNotEmpty(row.getCell(col))) {
                        sr = row.getCell(col).toString();
                        col++;
                        // 行次
                        if (ToolUtil.isNotEmpty(row.getCell(col))) {
                            hang = row.getCell(col).toString();
                            if(hang.contains(".")){
                                hang = hang.substring(0,hang.indexOf("."));
                            }
                            col++;
                        }
                        //获取单元格
                        for (int m = col; m <= maxCol; m++) {
                            Cell cell = row.getCell(m);
                            if (ToolUtil.isNotEmpty(cell)) {
                                cell.setCellType(CellType.STRING);
                            }
                            String dm =colIdDianmingMap.get(m);
                            if (ToolUtil.isNotEmpty(dm)) {
                                String zc = colIdXuhaoMap.get(m);//编号
                                logger.info("zc+~~~~~~~~~!!```!!~~~~~~~~~~:"+ zc );
                                logger.info("dm+~~~~~~~~~~~~~~~~~~~~~~~~~~:"+ dm );
                                if(!"本月金额:合计".equals(dm)&& !"".equals(dm)){
                                    dm = colIdDianmingMap.get(m).split(zc)[1];//店名
                                } else {
                                    dm = "本月合计";
                                }
                                String hm = row.getCell(m) == null ? "" : row.getCell(m).getStringCellValue();
                                BtyCWGainLoss btyCWGainLoss = new BtyCWGainLoss();
                                btyCWGainLoss.setId(UUIDUtils.getId());
                                btyCWGainLoss.setDm(dm);
                                btyCWGainLoss.setDate(date);
                                btyCWGainLoss.setNumber(zc);
                                btyCWGainLoss.setTitle(sr);
                                btyCWGainLoss.setHang(hang);
                                btyCWGainLoss.setType("1");
                                btyCWGainLoss.setMoney(hm);
                                btyCWGainLossMapper.deleteDM(btyCWGainLoss);
                                btyCWGainLossMapper.insert(btyCWGainLoss);
                            }
                        }
                    }
                }
            }
        }

        return notNull;
    }

    /**
     * 导入资产负债excel
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Boolean importZCFZ(String fileName, MultipartFile file) throws Exception {
        boolean notNull = false;
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        int sheets = wb.getNumberOfSheets();

        Map<Integer, String> colIdXuhaoMap = new HashMap<Integer, String>();
        Map<Integer, String> colIdDianmingMap = new HashMap<Integer, String>();

        int row_l = 1;
        for (int i = 0; i < sheets; i++) {
            Sheet sheet = wb.getSheetAt(i);
            if (sheet != null) {
                notNull = true;
            }
            int lastRowNum = sheet.getLastRowNum();
            String date = sheet.getRow(1).getCell(0).toString().split("会计期间：")[1];
            row_l++;

            int maxCol = 1;
            {
                int col = 3;
                Row row_bianhao = sheet.getRow(row_l);
                String number;
                Row row_mendian = sheet.getRow(row_l+1);
                String mendian;
                boolean isCon = true;
                do {
                    number = row_bianhao.getCell(col).toString();
                    if(number.contains(".")){
                        number = number.substring(0,number.indexOf("."));
                    }
                    if (ToolUtil.isNotEmpty(number) || "期末余额:合计".equals(sheet.getRow(row_l+1).getCell(col).toString())) {
                        colIdXuhaoMap.put(col, number);
                        mendian = row_mendian.getCell(col).toString();
                        colIdDianmingMap.put(col, mendian);
                    } else {
                        isCon = false;
                    }
                    col++;
                    maxCol++;
                } while (isCon);
            }

            row_l++;
            row_l++;

            for (int r = row_l; r <= lastRowNum; r++) {
                Row row = sheet.getRow(r);
                if (ToolUtil.isNotEmpty(row)) {
                    int col = 0;
                    String sr;
                    String hang = "";
                    //报表项目
                    if (ToolUtil.isNotEmpty(row.getCell(col))) {
                        sr = row.getCell(col).toString();
                        col++;
                        // 行次
                        if (ToolUtil.isNotEmpty(row.getCell(col))) {
                            row.getCell(col).setCellType(CellType.STRING);
                            hang = row.getCell(col).toString();
                            if(hang.contains(".")){
                                hang = hang.substring(0,hang.indexOf("."));
                            }
                            col++;
                        }
                        //获取单元格
                        for (int m = col; m <= maxCol; m++) {
                            Cell cell = row.getCell(m);
                            if (ToolUtil.isNotEmpty(cell)) {
                                cell.setCellType(CellType.STRING);
                            }
                            String dm = colIdDianmingMap.get(m);
                            if (ToolUtil.isNotEmpty(dm)) {
                                String zc = colIdXuhaoMap.get(m);//编号
                                if(!"期末余额:合计".equals(dm)){
                                    dm = colIdDianmingMap.get(m).split(zc)[1];//店名
                                } else {
                                    dm = "本月合计";
                                }
                                String hm = row.getCell(m) == null ? "" : row.getCell(m).getStringCellValue();
                                BtyCWGainLoss btyCWGainLoss = new BtyCWGainLoss();
                                btyCWGainLoss.setId(UUIDUtils.getId());
                                btyCWGainLoss.setDm(dm);
                                btyCWGainLoss.setDate(date);
                                btyCWGainLoss.setNumber(zc);
                                btyCWGainLoss.setTitle(sr);
                                btyCWGainLoss.setHang(hang);
                                btyCWGainLoss.setType("2");
                                btyCWGainLoss.setMoney(hm);
                                btyCWGainLossMapper.deleteDM(btyCWGainLoss);
                                btyCWGainLossMapper.insert(btyCWGainLoss);
                            }
                        }
                    }
                }
            }
        }
        return notNull;
    }
}
